package com.example.testapp.ui.balance

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.testapp.R
import com.example.testapp.data.entity.Balance
import com.google.android.material.floatingactionbutton.FloatingActionButton
import java.time.format.DateTimeFormatter

/**
 * 账单列表Fragment
 */
class BalanceListFragment : Fragment() {

    private lateinit var viewModel: BalanceViewModel
    private lateinit var adapter: BalanceAdapter
    private lateinit var recyclerView: RecyclerView
    private lateinit var emptyView: View
    private lateinit var loadingView: View

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val rootView = inflater.inflate(R.layout.fragment_balance_list, container, false)
        
        // 初始化视图
        recyclerView = rootView.findViewById(R.id.recyclerViewBalances)
        emptyView = rootView.findViewById(R.id.emptyView)
        loadingView = rootView.findViewById(R.id.loadingView)
        val fab = rootView.findViewById<FloatingActionButton>(R.id.fabAddBalance)

        // 设置RecyclerView
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        adapter = BalanceAdapter(ArrayList()) { balance -> onBalanceItemClick(balance) }
        recyclerView.adapter = adapter

        // 设置FAB点击事件
        fab.setOnClickListener {
            // 启动拍照界面
            navigateToCameraCapture()
        }

        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        // 初始化ViewModel
        viewModel = ViewModelProvider(requireActivity())[BalanceViewModel::class.java]
        
        // 观察账单列表数据
        viewModel.allBalances.observe(viewLifecycleOwner) { balances ->
            adapter.updateData(balances)
            
            // 更新空视图可见性
            if (balances.isNullOrEmpty()) {
                recyclerView.visibility = View.GONE
                emptyView.visibility = View.VISIBLE
            } else {
                recyclerView.visibility = View.VISIBLE
                emptyView.visibility = View.GONE
            }
        }
        
        // 观察操作状态
        viewModel.operationState.observe(viewLifecycleOwner) { state ->
            when (state) {
                is BalanceViewModel.OperationState.Loading -> {
                    loadingView.visibility = View.VISIBLE
                }
                is BalanceViewModel.OperationState.Success -> {
                    loadingView.visibility = View.GONE
                    Toast.makeText(requireContext(), state.message, Toast.LENGTH_SHORT).show()
                }
                is BalanceViewModel.OperationState.Error -> {
                    loadingView.visibility = View.GONE
                    Toast.makeText(requireContext(), state.message, Toast.LENGTH_SHORT).show()
                }
                else -> loadingView.visibility = View.GONE
            }
        }
    }

    /**
     * 账单项点击事件
     * @param balance 账单对象
     */
    private fun onBalanceItemClick(balance: Balance) {
        // 导航到账单详情页
        balance.id?.let { navigateToBalanceDetail(it) }
    }

    /**
     * 导航到相机拍摄页面
     */
    private fun navigateToCameraCapture() {
        // TODO: 使用Navigation组件导航到相机页面
        // findNavController().navigate(R.id.action_balanceListFragment_to_cameraFragment)
    }

    /**
     * 导航到账单详情页
     * @param balanceId 账单ID
     */
    private fun navigateToBalanceDetail(balanceId: Long) {
        // TODO: 使用Navigation组件导航到详情页，传递balanceId参数
        // val bundle = Bundle().apply { putLong("balanceId", balanceId) }
        // findNavController().navigate(R.id.action_balanceListFragment_to_balanceDetailFragment, bundle)
    }

    /**
     * 账单适配器
     */
    private class BalanceAdapter(
        private var balances: List<Balance>,
        private val listener: (Balance) -> Unit
    ) : RecyclerView.Adapter<BalanceAdapter.ViewHolder>() {
        
        private val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_balance, parent, false)
            return ViewHolder(view)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val balance = balances[position]
            holder.bind(balance, listener)
        }

        override fun getItemCount(): Int = balances.size

        fun updateData(newBalances: List<Balance>) {
            this.balances = newBalances
            notifyDataSetChanged()
        }

        class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            private val textAmount: TextView = itemView.findViewById(R.id.textAmount)
            private val textCategory: TextView = itemView.findViewById(R.id.textCategory)
            private val textDate: TextView = itemView.findViewById(R.id.textDate)
            private val textDescription: TextView = itemView.findViewById(R.id.textDescription)
            
            fun bind(balance: Balance, listener: (Balance) -> Unit) {
                textAmount.text = formatAmount(balance.amount)
                textCategory.text = balance.categoryName ?: ""
                textDate.text = balance.billDate?.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) ?: ""
                textDescription.text = balance.description ?: ""
                
                itemView.setOnClickListener { listener(balance) }
            }
            
            private fun formatAmount(amount: Int?): String {
                return if (amount == null) {
                    "¥0.00"
                } else {
                    String.format("¥%.2f", amount / 100.0)
                }
            }
        }
    }
} 